package com.hz.sys.config;

import com.hz.beans.code.HzResultCode;
import com.hz.sys.utils.ResponseUtils;
import com.hz.sys.utils.WebUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author mcz
 * @Date 2018/10/26 15:18
 * @Description 全局异常配置
 * @Version 1.0
 */
@Component
@Configuration
public class GlobalExceptionConfig implements HandlerExceptionResolver {

    private Logger logger=LoggerFactory.getLogger(GlobalExceptionConfig.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        logger.error("异常{}",ex.toString());
        ResponseUtils responseUtils=new ResponseUtils();
        responseUtils.setResponseDesc(HzResultCode.SYSTEM_EXCEPTION.getResultDesc());
        if(ex instanceof RuntimeException){
            if(WebUtil.isAjaxRequest()){
                WebUtil.writeJson(response,responseUtils.failJSON(responseUtils));
            }else{
                ModelAndView modelAndView=new ModelAndView();
                response.setContentType("text/html;charset=utf-8");
                modelAndView.addObject("model",responseUtils);
                modelAndView.setViewName("page/error/500");
                return modelAndView;
            }
        }
        return null;
    }
}
